<?php
session_start();
require_once __DIR__.'/../../model/UserModel.php';
require_once __DIR__.'/../../utils/PasswordUtils.php';
use model\UserModel;
use utils\PasswordUtils;

$username=trim($_POST['username']??'');
$password=trim($_POST['password']??'');
$errors=[];

if (empty($username) || strlen($username) < 3 || strlen($username) > 10) {
    $errors[] = '用户名需为3-10位字符';
}
if (empty($password) || strlen($password) < 4 || strlen($password) > 16) {
    $errors[] = '密码需为4-16位字符';
}

if (empty($errors)) {
    // 查询用户
    $userModel = new UserModel();
    $user = $userModel->getUserByUsername($username);

    if (!$user) {
        $errors[] = '用户不存在';
    } else {
        // 验证密码
        if (!PasswordUtils::verify($password, $user['password'])) {
            $errors[] = '密码错误';
        }
    }
}

if (empty($errors)) {
    // 登录成功，设置session
    $_SESSION['user'] = [
        'id' => $user['id'],
        'username' => $user['username'],
        'role' => $user['role']
    ];

    if ($user['role']==1){
        $_SESSION['success_message'] = '登录成功';
        header('Location: /bookprogram/src/view/books/Books.php');
    }elseif ($user['role']==0){
        $_SESSION['success_message'] = '登录成功';
        header('Location: /bookprogram/public/index.php');
    }

} else {
    // 登录失败，记录错误信息
    $_SESSION['error_message'] = implode('<br>', $errors);
    header('Location: /bookprogram/src/view/login/login.php');
}
exit;